package com.school.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.school.pojo.Account;
import com.school.pojo.Student;
import com.school.pojo.Teacher;
import com.school.service.AccountService;
import com.school.service.StudentService;
import com.school.service.TeacherService;
import com.school.util.Result;

@RequestMapping("/account")
@RestController
public class AccountController {
	
	@Autowired
	private AccountService accountService;
	
	@Autowired
	private StudentService studentService;
	
	@Autowired
	private TeacherService teacherService;
	
	@RequestMapping("/findAll")
	public Result<Account> findAll(){
		List<Account> accounts= accountService.findAll();
		Result<Account> result=new Result<Account>();
		result.setList(accounts);
		return result;
	}
	
	@RequestMapping("/findByUsernameAndPassword")
	public int findByUsernameAndPassword(Account account,HttpServletRequest request,HttpServletResponse response){
		Account account2= accountService.findByUsernameAndPassword(account);
		
		request.getSession().setAttribute("account", account2);

		if(account2!=null) {
			if(account2.getStatus()==0) {
				//管理员
				return 0;
			}else {
				//其他
				return 1;
			}
		}else {
			return 2;
		}
		
	}
	
	@RequestMapping("/extract")
	public Map<String, Object> extract(HttpServletRequest request,HttpServletResponse response){
		Account account= (Account)request.getSession().getAttribute("account");
		
		Student student= studentService.findByAId(account.getAccount_id());
		Map<String, Object> map=new HashMap<String, Object>();
		
		if(student.getName()!=null) {
			map.put("data", student);
		}else {
			Teacher teacher= teacherService.findByAId(account.getAccount_id());
			map.put("data", teacher);
		}
		
		System.out.println(map);
		
		return map;
	}
	
	@RequestMapping("/eliminate")
	public void eliminate(HttpServletRequest request,HttpServletResponse response) {
		request.getSession().setAttribute("account", null);
	}
	
	@RequestMapping("/findById")
	public Result<Account> findById(int id) {
		Result<Account> result=new Result<Account>();
		result.setData(accountService.findById(id));
		return result;
	}
	
}
